using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.XPath;
using LibrairieBahaMen.Xml;

namespace LibrairieBahaMen.Xml
{
    class Rss
    {
        
        /*string path = "";
        path.Replace("%s",serieName);
        path.Replace("%r",quality);
        path.Replace("%f",repositoryRSS);*/

        public static IList<string> GetUrlTorrentFromAbonnement(ref Int32 episodeSaison, ref Int32 episodeNum, string urlTorrents, string itemToIterate)
        {
            IList<string> files = new List<string>();
            IList<XPathNavigator> x_episodes = XmlUtil.SelectTags(urlTorrents, itemToIterate);

            IDictionary<string, string> episode;
            Int32 maxEpisodeSaison = episodeSaison;
            Int32 maxEpisodeNum = episodeNum;

            foreach(XPathNavigator x_episode in x_episodes){
                //On itere sur tous les items du flux RSS
                episode = XmlUtil.SelectChildsFromNode(x_episode);

                Regex regName = new Regex(@"([0-9]{1,2})x([0-9]{1,2})");
                Match monMatch = regName.Match(episode["title"]);
                if (monMatch.Success)
                    if ((Int32.Parse(monMatch.Groups[1].Value) == episodeSaison && Int32.Parse(monMatch.Groups[2].Value) > episodeNum) || (Int32.Parse(monMatch.Groups[1].Value) > episodeSaison)) {
                        //On ajoute l' url du torrent dans la liste des telechargements

                        files.Add(Regex.Replace(episode["link"], "mininova.org/tor/", "mininova.org/get/"));

                        if (maxEpisodeSaison < Int32.Parse(monMatch.Groups[1].Value)){
                            maxEpisodeSaison = Int32.Parse(monMatch.Groups[1].Value);
                            maxEpisodeNum = Int32.Parse(monMatch.Groups[2].Value);
                        }
                        else if (maxEpisodeNum < Int32.Parse(monMatch.Groups[2].Value))
                        {
                            maxEpisodeNum = Int32.Parse(monMatch.Groups[2].Value);
                        }
                    } else
                        break;
                
            }
            episodeSaison = maxEpisodeSaison;
            episodeNum = maxEpisodeNum;
            return files;
        }
    }
}
